//
//  ViewA.m
//  drag
//
//  Created by 梁羽 on 2025/6/28.
//

#import "ViewA.h"

@implementation ViewA

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        
        
#if 0
        // 创建视图B并添加到视图A中
        _viewB = [[ViewB alloc] initWithFrame:CGRectMake(50, 50, 200, 200)];
        _viewB.containerView = self; // 设置容器视图
        [self addSubview:_viewB];
#elif 1
        // 创建视图D（直线）
        _viewD = [[ViewD alloc] initWithFrame:CGRectMake(50, 50, 200, 200)];
        _viewD.lineColor = [UIColor purpleColor];
        [self addSubview:_viewD];
#else
        // 创建ViewC并添加到ViewA中
        _viewC = [[ViewC alloc] initWithFrame:CGRectMake(50, 50, 200, 200)];
        _viewC.containerView = self;
        [self addSubview:_viewC];
#endif
        
        // 创建菜单栏
        _menuBar = [[MenuBarView alloc] initWithFrame:CGRectMake(0, 0, 270, 40)];
        [self addSubview:_menuBar];
        [self updateMenuBarPosition];
    }
    return self;
}

- (void)updateMenuBarPosition {
    UIView *tview;
    if (self.viewB) {
        tview = self.viewB;
    }
    if (self.viewC) {
        tview = self.viewC;
    }
    // 计算菜单栏应该在视图B的上方还是下方
    CGFloat spaceAbove = CGRectGetMinY(tview.frame) - 10;
    CGFloat spaceBelow = CGRectGetHeight(self.frame) - CGRectGetMaxY(tview.frame) - 10;
    
    if (spaceAbove >= 40) {
        // 放在上方
        self.menuBar.center = CGPointMake(CGRectGetMidX(tview.frame), CGRectGetMinY(tview.frame) - 20 - CGRectGetHeight(self.menuBar.frame)/2);
    } else if (spaceBelow >= 40) {
        // 放在下方
        self.menuBar.center = CGPointMake(CGRectGetMidX(tview.frame), CGRectGetMaxY(tview.frame) + 20 + CGRectGetHeight(self.menuBar.frame)/2);
    } else {
        // 如果上下空间都不够，默认放在下方
        self.menuBar.center = CGPointMake(CGRectGetMidX(tview.frame), CGRectGetMaxY(tview.frame) + 20 + CGRectGetHeight(self.menuBar.frame)/2);
    }
}

@end
